from django.conf import settings
from django.contrib.auth.backends import ModelBackend
import re

from itsdangerous import TimedJSONWebSignatureSerializer as serializer, BadData
from users.models import User

def get_user_mobile(acount):
    try:
        if re.match(r'1[345789]\d{9}',acount):
            user = User.objects.get(mobile=acount)
            # 注意get里面的传参形式，get(acount)->报错 ValueError: too many values to unpack
            # 找到get返回一个对象，找不到get返回一个none值
        else:
            user = User.objects.get(username=acount)
    except User.DoesNotExist:
        return None
    return user

class UsernameMobileBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        user = get_user_mobile(username)
        if user and user.check_password(password):
            return user


def get_encryped_url(user):
    '''对邮箱验证路由进行加密'''
    serialize_obj = serializer(settings.SECRET_KEY,3600)
    # 目的是把用户的唯一标识和邮箱传过去，然后后续再接受，跟数据库中的数据比对
    data = {'id':user.id,'email':user.email}
    token = serialize_obj.dumps(data).decode()
    verify_url =settings.EMAIL_VERIFY_URL + '?token=' + token
    return verify_url

def check_url(token):
    '''对邮箱验证路由传来的token解密并提取出email'''
    serialize_obj = serializer(settings.SECRET_KEY,3600)
    try:
        user = serialize_obj.loads(token)
        user_id = user.get('id')
        user_email = user.get('email')
        return user_id ,user_email
    except BadData:
        return None
